package com.zdc.learn.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * netty 服务端业务处理handler
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("读取数据ing.................................");
        ByteBuf byteBuffer = (ByteBuf) msg;
        System.out.println("当前线程："+Thread.currentThread().getName());
        System.out.println("读取到的数据....:"+byteBuffer.toString(CharsetUtil.UTF_8));
//       添加线程队列。。。。
//        ctx.channel().eventLoop().execute(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        });

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("数据处理完成。。。。。。。。。。。。。。。。。");
        String msg = "你好 我已收到";
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("服务端异常："+cause);
    }
}
